package com.gitee.xmhzzz.component.web.exception;

import com.gitee.xmhzzz.component.common.dto.BaseResult;
import com.gitee.xmhzzz.component.common.enums.ResponseCode;
import com.gitee.xmhzzz.component.common.exception.AbstractBusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

/**
  * @ClassName
  * @Description
  * @Author wzq
  * @Date 2023/12/18 10:21
  * @Version 1.0
  */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 异常捕获
     *
     * @param e 异常
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public BaseResult<Object> exceptionHandler(Exception e) {
        Logger logger = LoggerFactory.getLogger((Objects.nonNull(e.getStackTrace()) && e.getStackTrace().length > 0) ? e.getStackTrace()[0].getClassName() : GlobalExceptionHandler.class.getName());

        BaseResult ret;
        if (e instanceof MissingServletRequestParameterException || e instanceof HttpMessageConversionException) {
            ret = BaseResult.fail(ResponseCode.BAD_REQUEST);
            logger.warn("请求参数错误：{}", e.getMessage());
        } else if (e instanceof MethodArgumentNotValidException) {
            ret = BaseResult.fail(ResponseCode.BAD_REQUEST);
            // 数据验证错误提示
            MethodArgumentNotValidException vex = (MethodArgumentNotValidException) e;
            FieldError fieldError = vex.getBindingResult().getFieldErrors().get(0);
            String msg = String.format("请求参数错误, [%s]%s", fieldError.getField(), fieldError.getDefaultMessage());
            ret.setMessage(fieldError.getDefaultMessage());
            logger.warn("{} - {}", msg, e.getMessage());
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            ret = BaseResult.fail(ResponseCode.METHOD_NOT_ALLOWED);
            logger.warn("不支持的请求: {}", e.getMessage());
        } else if (e instanceof AbstractBusinessException) {
            AbstractBusinessException businessException = (AbstractBusinessException) e;
            ret = BaseResult.fail(businessException.getResponseCode(), businessException.getMessage());
            logger.warn("业务异常", e);
        } else if (e instanceof DuplicateKeyException) {
            ret = BaseResult.fail(ResponseCode.DUPLICATE_KEY_EXCEPTION);
            logger.warn("数据库唯一索引异常", e);
        } else {
            ret = BaseResult.fail(ResponseCode.SYSTEM_BUSY);
            logger.error("服务异常：", e);
        }

        return ret;
    }
}
